package com.rfid.a252robot.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.AnimatedImageDrawable;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rfid.a252robot.R;
import com.rfid.a252robot.activity.adapter.BookAdapter;
import com.rfid.a252robot.activity.adapter.BookItemAdapter;
import com.rfid.a252robot.activity.presenter.RestorePresenter;
import com.rfid.a252robot.activity.view.IRestoryView;
import com.rfid.a252robot.base.BaseActivity;
import com.rfid.a252robot.base.BaseListActivity;
import com.rfid.db.bean.Book;
import com.rfid.mqtt.MqttManager;
import com.rfid.util.Util;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RestoreActivity extends BaseActivity<RestorePresenter> implements IRestoryView {

    List<Book> mBooks = new ArrayList<>();
    List<Book> mRestoreBooks = new ArrayList<>();
    @BindView(R.id.tip)
    TextView mTipView;
    @BindView(R.id.ct)
    TextView mCTView;
    @BindView(R.id.complete)
    Button mComplete;
    CountDownTimer mTimer;
    int mBoxNum;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    BookItemAdapter mAdapter;

    @BindView(R.id.left_arrow)
    ImageView mLeft;
    @BindView(R.id.right_arrow)
    ImageView mRight;
    @BindView(R.id.restore)
    Button mRestore;
    @BindView(R.id.reopen)
    Button mReopen;

    boolean isRestoreFail;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_restore);
        ButterKnife.bind(this);
        mLeft.setVisibility(View.GONE);
        mRight.setVisibility(View.GONE);
        mAdapter = new BookItemAdapter(mBooks);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mAdapter);

        new AlertDialog.Builder(this)
                .setTitle("还书须知")
                .setMessage("1.本设备只支持归还北京公共图书馆图书。其他图书馆图书无法归还\n\n" +
                        "2.一个书格最多一次性归还三本。否则无法归还\n\n" +
                        "3.归还图书后请到屏幕前确定还书数量是否一致，点击确认后再离开。")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String tip = mPresenter.restore();
                        if (!TextUtils.isEmpty(tip)) {
                            mTipView.setText(tip);
                        }
                        mTimer = new CountDownTimer(60000,1000) {
                            @Override
                            public void onTick(long millisUntilFinished) {
                                mCTView.setText((millisUntilFinished/1000) + "s");
                            }

                            @Override
                            public void onFinish() {
                                onTimeFinish();
                            }
                        };
                        mTimer.start();
                    }
                })
                .show();
    }

    protected void resetCountDownTime(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = new CountDownTimer(60000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    mCTView.setText((millisUntilFinished/1000) + "s");
                }

                @Override
                public void onFinish() {
                    onTimeFinish();
                }
            };
            mTimer.start();
        }
    }

    @Override
    protected void onTimeFinish() {
        finish();
    }

    @Override
    protected int getCountDownTime() {
        return -1;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public RestorePresenter getPresenter() {
        return new RestorePresenter();
    }


    @Override
    public void showLoading() {
    }

    @Override
    public void hideLoading() {
    }

    @Override
    public void onBoxOpen(int boxNum,boolean s) {
        if (isRestoreFail) {
            return;
        }
        mBoxNum = boxNum;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                String tip = null;
                if (s) {
                    tip = String.format("柜门已打开，\n请将要还的图书放入%s号柜", Util.getBoxShow(boxNum));
                    mTipView.setText(tip);
                    if (boxNum > 28) {
                        mLeft.setVisibility(View.VISIBLE);
                        ((AnimationDrawable)mLeft.getDrawable()).start();
                    } else {
                        mRight.setVisibility(View.VISIBLE);
                        ((AnimationDrawable)mRight.getDrawable()).start();
                    }
                } else {
                    tip = String.format("%s号柜门打开失败，请重试",Util.getBoxShow(boxNum));
                    mTipView.setText(tip);
                    mComplete.setEnabled(true);
                    mRestore.setEnabled(true);
                }
                MqttManager.INSTANCE.sendVoice(tip);
            }
        },500);

    }

    @Override
    public void onBoxClose(int boxNum) {
        if (mBoxNum == boxNum) {
            mTipView.setText("请核对图书,若无法识别，请到服务台归还");
//            finish();
        }
        mComplete.setEnabled(true);
        mRestore.setEnabled(true);
        mReopen.setEnabled(true);
    }

    @Override
    public void onBookInfos(List<Book> books) {
        System.out.println("onBookInfos = " + books);
        mBooks.clear();
        mBooks.addAll(books);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onBookRestore(Book book) {
        System.out.println("onBookRestore = " + book);
        mRestoreBooks.add(book);
        mBooks.clear();
        mBooks.addAll(mRestoreBooks);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onBookRestoreFail(String msg) {
        isRestoreFail = true;
        mTipView.setText(msg);
        MqttManager.INSTANCE.sendVoice(msg);
    }

    @OnClick(R.id.complete)
    public void complete(View view) {
        mTimer.cancel();
        finish();
    }
    @OnClick(R.id.restore)
    public void restore(View v){
        mPresenter.doRestore(mBooks);
        finish();
    }
    @OnClick(R.id.reopen)
    public void reopen(View v){
        mRestore.setEnabled(false);
        mReopen.setEnabled(false);
        mPresenter.reopen(mBoxNum);
    }

    @Override
    protected int getWaitTime() {
        return 60000;
    }
}
